package com.chen10.gobang.config.interceptor;

import com.chen10.gobang.common.enums.response.ErrorEnum;
import com.chen10.gobang.common.exception.BusinessException;
import com.chen10.gobang.common.protocal.ResponseResult;
import com.chen10.gobang.common.protocal.ResponseVO;
import com.chen10.gobang.common.utils.JwtUtil;
import com.chen10.gobang.common.utils.StringTools;
import com.chen10.gobang.common.utils.UserThreadLocal;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);
    private static final String BEARER_PREFIX = "Bearer ";
    private final ObjectMapper objectMapper;


    public JwtInterceptor(final ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String api = StringTools.getApi(request.getRequestURL().toString());
//        log.info("请求api: {}", api);
        String token = request.getHeader("Authorization");
        //log.info("Request token: {}", token);
        if (token != null && !token.equals("")) {
        }
        // 处理 OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        try {
            if (!StringUtils.hasText(token)) {
                log.info("未携带token");
                throw new BusinessException(ErrorEnum.UNAUTHORIZED);
            } else if (!token.startsWith("Bearer ")) {
                log.info("token格式错误");
                throw new BusinessException(ErrorEnum.TOKEN_FORMAL_ERROR);
            } else {
                token = token.substring("Bearer ".length());
                if (JwtUtil.verifyToken(token) && !JwtUtil.isTokenExpired(token)) {
//                    log.info("token剩余时长:{}", JwtUtil.getTokenRemainingTime(token));
                    UserThreadLocal.setUserId(JwtUtil.getUserIdFromToken(token));
                    return true;
                } else {
                    log.info("token无效或已过期");
                    throw new BusinessException(ErrorEnum.TOKEN_INVALID_OR_EXPIRED);
                }
            }
        } catch (BusinessException var9) {
            response.setStatus(var9.getCode());
            response.setContentType("application/json;charset=UTF-8");
            ResponseVO<?> errorResponse = ResponseResult.error(var9.getCode(), var9.getMessage());

            try {
                response.getWriter().write(this.objectMapper.writeValueAsString(errorResponse));
            } catch (IOException var8) {
                var8.printStackTrace();
            }

            return false;
        }
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserThreadLocal.clear();
    }
}
